package com.quanyan.ic.video.task.job;

import com.alibaba.fastjson.JSON;
import com.github.ltsopensource.core.domain.Action;
import com.github.ltsopensource.tasktracker.Result;
import com.github.ltsopensource.tasktracker.runner.JobContext;
import com.github.ltsopensource.tasktracker.runner.JobRunner;
import com.quanyan.ic.video.http.cache.Hik8710EventDAO;
import com.quanyan.ic.video.http.service.Hik8710EventService;
import com.quanyan.ic.video.model.hik8710.Hik8710Event;
import com.quanyan.ic.video.task.TimerTaskJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * Created by zhuo.shi on 2017/8/18.
 */
@Component
public class Hik8710_131331StartEventCheckJob implements JobRunner {

    private static final Logger logger = LoggerFactory.getLogger(Hik8710_131331StartEventCheckJob.class);

    @Autowired
    @Qualifier("131331")
    private Hik8710EventService hik8710EventService;
    @Autowired
    private TimerTaskJob timerTaskJob;
    @Autowired
    private Hik8710EventDAO hik8710EventDAO;

    @Override
    public Result run(JobContext jobContext) throws Throwable {
        String taskId = jobContext.getJob().getTaskId();
        Map<String, String> params = jobContext.getJob().getExtParams();
        logger.info("execute job: {}, {}", taskId, params);

        Hik8710Event event = JSON.parseObject(params.get("event"), Hik8710Event.class);
        if (!hik8710EventDAO.exsitStartEventTag(event.getEvent_id())) {
            logger.info("startEvent tag is delete ignore");
            return new Result(Action.EXECUTE_SUCCESS);
        }

        event.setMock(true);
        event.setState((byte) 2);
        event.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        hik8710EventService.handleEvent(event);

        params.put("event", JSON.toJSONString(event));
        long executeTime = System.currentTimeMillis() + hik8710EventDAO.get131331EventParam_AlarmLimitTime();
        timerTaskJob.submitTask(params, taskId, executeTime, 0L);
        logger.info("submit startEvent task: {}, will execute at {}", taskId, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(executeTime)));

        return new Result(Action.EXECUTE_SUCCESS);
    }

}
